package com.oss.view;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import junit.framework.Assert;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.oss.client.dto.BaseRequest;
import org.oss.client.dto.OssSecurityRequest;
import org.oss.client.dto.OssSecurityResponse;
import org.oss.client.dto.UrlResponse;
import org.oss.util.JsonMapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.opensymphony.xwork2.ActionSupport;
import com.oss.base.OssMethod;
import com.oss.base.util.HttpUtil;
import com.oss.base.util.SignUtil;
import com.oss.service.IStorageService;
import com.oss.service.IUserService;
import com.oss.vo.SysUser;
import com.oss.vo.UserAuth;

public class OssSecurityAction extends ActionSupport{
	/** serialVersionUID*/
	private static final long serialVersionUID = 4891704509156504182L;

	Logger logger = Logger.getLogger(this.getClass());
	
	public String req;
	@Autowired
	IUserService userService;
	@Autowired
	private IStorageService storageService;
	
	@Action("GetSecurity")
	public void getSecurity(){
		long begin = System.currentTimeMillis();
		OssSecurityRequest reqObj = JsonMapper.buildNonDefaultMapper().fromJson(req, OssSecurityRequest.class);
		
		try {
			SysUser user = userService.getUserByLoginName(reqObj.getUser());
			String fileId = storageService.saveFileInfo(reqObj,user);
			
			OssSecurityResponse res = userService.getUserSecurity(user, reqObj);
			res.setFileId(fileId);
			
			HttpUtil.writeRes(res);
		} catch (Exception e) {
			e.printStackTrace();
			HttpUtil.writeRes(HttpUtil.buildFailedRes(UrlResponse.class, e));
		}
		
		long end = System.currentTimeMillis();
	    logger.info("server耗时:"+(end-begin));
	}
	
	
	@Action("sign")
	public void sign(){
		
		OssSecurityRequest reqObj = JsonMapper.buildNormalMapper().fromJson(req, OssSecurityRequest.class);
		SysUser user = userService.getUserByLoginName(reqObj.getUser());
		reqObj.setMethod(OssMethod.POST_OBJECT);
		String fileId = storageService.saveFileInfo(reqObj,user);
		UserAuth auth = userService.getUserAuth(user, reqObj);
	
		SimpleDateFormat dft=new SimpleDateFormat("yyyyMMdd");    
		String date = dft.format(new Date());
		
		String endpoint = auth.getEndpoint();
        String accessId = auth.getAccConfig().getAccId();
        String accessKey = auth.getAccConfig().getAccSecret();
        String bucket = auth.getBucket();
//        String dir = auth.getAccPath()+date+"/"+fileId+"-"+reqObj.getFileName();
        String dir = auth.getAccPath();
        String host = "http://"+endpoint+"/"+bucket;
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        try { 	
        	long expireTime = 30;
        	long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
//            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
//            String postPolicy ="{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}";
            
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
//            String postSignature =SignUtil.b64_hmac_sha1(accessKey, postPolicy);
            
            String postSignature = client.calculatePostSignature(postPolicy);
            
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            //respMap.put("expire", formatISO8601Date(expiration));
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
           System.out.println(postSignature);
           System.out.println(postPolicy);
           System.out.println(encodedPolicy);
           System.out.println(accessId);
            StringBuffer callback = new StringBuffer()
            .append("{\"callbackUrl\":\"oss-demo.aliyuncs.com:23450\",")
            .append("\"callbackHost\":\"oss-demo.aliyuncs.com\",")
            .append("\"callbackBody\":\"filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}\",")
            .append("\"callbackBodyType\":\"application/x-www-form-urlencoded\"}");
            
//            
//            /**
//             *   StringBuffer callback = new StringBuffer()
//            .append("{\"callbackUrl\":\"127.0.0.1:8080/oss-web/t.shtml\",")
//            .append("\"callbackHost\":\"127.0.0.1:8080\",")
//            .append("\"callbackBody\":\"filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}\",")
//            .append("\"callbackBodyType\":\"application/x-www-form-urlencoded\"}");
//             * 
//             */
//            
//            
            respMap.put("callback", BinaryUtil.toBase64String(callback.toString().getBytes("UTF-8")));
           	ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin", "*");
           	ServletActionContext.getResponse().setHeader("Access-Control-Allow-Methods", "GET, POST");
            ServletActionContext.getResponse().setContentType("text/json;charset=UTF-8");
			ServletActionContext.getResponse().getWriter().write(JsonMapper.buildNonDefaultMapper().toJson(respMap));
			ServletActionContext.getResponse().getWriter().flush();
            
            
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
	}
	
	public static void main(String[] args) {
		OssSecurityRequest req = new OssSecurityRequest();
		req.setUser("test");
		req.setFileName("fdfdsfs");
		String a = "{\"user\":\"test\",\"fileName\":\"fsdfds\"}";
		System.out.println(JsonMapper.buildNormalMapper().fromJson(a, BaseRequest.class));
		System.out.println(JsonMapper.buildNonDefaultMapper().toJson(req));
		
	}
	
}
